//
//  SetViewController.m
//  AAIM
//
//  Created by 远的小布丁 on 2019/12/3.
//  Copyright © 2019 AAIM. All rights reserved.
//

#import "SetViewController.h"
#import "SetFirstTableViewCell.h"
#import "SetSecondTableViewCell.h"
#import "ChangePasswordViewController.h"
#import "BlackListViewController.h"
#import <UserNotifications/UserNotifications.h>
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

@interface SetViewController ()<UITableViewDelegate,UITableViewDataSource,setFirstCellDelegate,CNContactPickerDelegate>
@property (nonatomic,strong) UITableView * setTableView;
@property (nonatomic,strong) NSArray * titleAry;
@property (nonatomic,strong) UIView * footView;
@property (nonatomic,strong) UIButton * signOutBtn;
@property (nonatomic,assign)NSInteger  isCheck;//1加好友需要审核后通过，0直接通过
//@property (nonatomic,assign)NSInteger isRecommend;//1推荐通讯录好友，0不推荐
@property (nonatomic,assign)NSInteger isMegPush;//1开启，0关闭消息推送
@property (nonatomic,strong) UserModel * model;
@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"设置";
    [self.view addSubview:self.setTableView];
    _titleAry = @[@"加我为好友需要验证",@"开启系统通知",@"修改密码",@"黑名单"];
    
    [self getUserInfoSet];

//    _isRecommend = [[[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"recommendFriends_%@",UserFuuid]] integerValue];
    _isMegPush = [[[NSUserDefaults standardUserDefaults]objectForKey:[NSString stringWithFormat:@"pushMsg_%@",UserFuuid]] integerValue];
    if (!_isMegPush) {
        [self getSystemMesSet];
    }
}

- (void)getUserInfoSet{
    _model = [LoginManager shareLoginManager].userModel;
    [RequestData GetUserInfoWithToken:_model.token userUUid:_model.uuid fuuid:_model.fuuid Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"个人信息：%@",Dict);
     
        if ([Dict[@"code"] integerValue] == 200) {
            KWeakSelf;
            weakSelf.model.isVerify = Dict[@"data"][@"isVerify"];
            weakSelf.isCheck = [Dict[@"data"][@"isVerify"] integerValue];
            [[NSUserDefaults standardUserDefaults] setObject:Dict[@"data"][@"isVerify"] forKey:[NSString stringWithFormat:@"checkFriends_%@",UserFuuid]];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[LoginManager shareLoginManager] saveLoginCustomer:weakSelf.model];
            NSLog(@"--------：%@",[LoginManager shareLoginManager].userModel.isVerify);
            [self.setTableView reloadData];
        }
    } failure:^(NSString * _Nonnull errMsg) {
        //        NSLog(@"出错了：%@",errMsg);
        [self showTipHudWithText:@"网络异常，稍后再试"];
    }];
}

- (void)getSystemMesSet{
    KWeakSelf;
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if(settings.authorizationStatus==UNAuthorizationStatusNotDetermined) {
                
                NSLog(@"未选择---没有选择允许或者不允许，按不允许处理");
                weakSelf.isMegPush = 0;
            }else if(settings.authorizationStatus==UNAuthorizationStatusDenied){
                
                NSLog(@"未授权--不允许推送");
                weakSelf.isMegPush = 0;
            }else if(settings.authorizationStatus==UNAuthorizationStatusAuthorized){
                weakSelf.isMegPush = 1;
                NSLog(@"已授权--允许推送");
                
            }
            
        }];
    } else {
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        
        if (UIUserNotificationTypeNone == setting.types) {
            
            NSLog(@"推送关闭");
            weakSelf.isMegPush = 0;
        }else{
            weakSelf.isMegPush = 1;
            NSLog(@"推送打开");
            
        }
    }
//    if (self.setTableView) {
//            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
//            [_setTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
//    }

    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld",_isMegPush] forKey:[NSString stringWithFormat:@"pushMsg_%@",UserFuuid]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.gk_navigationBar.gk_navLineHidden = NO;
}

//返回
- (void)BackActive:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleAry.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row <2) {
        SetFirstTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SetFirstCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"SetFirstTableViewCell" owner:self options:nil].firstObject;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        if (indexPath.row == 0) {
            if (_isCheck == 1) {
                [cell.swithBtn setSelected:YES];
            }else{
                [cell.swithBtn setSelected:NO];
            }
        }
//        else if (indexPath.row == 1){
//            if (_isRecommend == 1) {
//                [cell.swithBtn setSelected:YES];
//            }else{
//                [cell.swithBtn setSelected:NO];
//            }
//        }
        else{
           if (_isMegPush == 1) {
                [cell.swithBtn setSelected:YES];
            }else{
                [cell.swithBtn setSelected:NO];
            }
        }
        
        cell.titleNameLabel.text = _titleAry[indexPath.row];
        return cell;
    }else{
        SetSecondTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SetSecondCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"SetSecondTableViewCell" owner:self options:nil].firstObject;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleNameLabel.text = _titleAry[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 8.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 100.f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    [self.footView addSubview:self.signOutBtn];
    
    [_signOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.footView.mas_centerX);
        make.top.equalTo(self.footView.mas_top).offset(30.f);
        make.size.mas_equalTo(CGSizeMake(SCALAE_WIDTH(345.f), 40.f));
    }];
    return self.footView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 2) {
        ChangePasswordViewController * changeVC = [[ChangePasswordViewController alloc]init];
        [self.navigationController pushViewController:changeVC animated:YES];
    }else if (indexPath.row == 3){
        BlackListViewController * blackVC = [[BlackListViewController alloc]init];
        [self.navigationController pushViewController:blackVC animated:YES];
    }
}

//cell代理
- (void)checkSwithBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
    SetFirstTableViewCell *cell = (SetFirstTableViewCell *)[[sender superview] superview];
    // 获取cell的indexPath
    NSIndexPath *indexPath = [self.setTableView indexPathForCell:cell];
    NSLog(@"点击的是第%ld行按钮",indexPath.row);
    
    if (cell.swithBtn.selected) {
        [cell.swithBtn setSelected:YES];
        //        [cell.swithBtn setBackgroundImage:[UIImage imageNamed:@"打开"] forState:UIControlStateSelected];
        if (indexPath.row == 0 ) {
            _isCheck = 1;
            [self uploadSetDataWithData:@"1"];
        }
//        else if (indexPath.row == 1){
//            _isRecommend = 1;
//            [self getMailListAction:1];
//        }
        else if (indexPath.row == 1){
            _isMegPush = 1;
            [self setSystemPushMsg];
        }
        
        
    }else{
        //         [cell.swithBtn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
        [cell.swithBtn setSelected:NO];
        if (indexPath.row == 0 ) {
            _isCheck = 0;
            [self uploadSetDataWithData:[NSString stringWithFormat:@"%ld",_isCheck]];
        }
//        else if (indexPath.row == 1){
//            _isRecommend = 0;
//            [self getMailListAction:0];
//        }
        else if (indexPath.row == 1){
            _isMegPush = 0;
            [self setSystemPushMsg];
        }
        
    }
    

//    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld",_isRecommend] forKey:[NSString stringWithFormat:@"recommendFriends_%@",UserFuuid]];

 
}
////获取通讯录
//- (void)getMailListAction:(NSInteger )commend {
//    KWeakSelf;
//    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//    if (status == CNAuthorizationStatusNotDetermined) {
//        CNContactStore *store = [[CNContactStore alloc] init];
//        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
//            if (error) {
//                //无权限
//                weakSelf.isRecommend = 0;
//                [self showAlertViewAboutNotAuthorAccessContact];
//            } else {
//                //有权限
//                weakSelf.isRecommend = 1;
//                [self openContact];
//            }
//        }];
//    } else if(status == CNAuthorizationStatusRestricted) {
//        //无权限
//        weakSelf.isRecommend = 0;
//        [self showAlertViewAboutNotAuthorAccessContact];
//    } else if (status == CNAuthorizationStatusDenied) {
//        //无权限
//        weakSelf.isRecommend = 0;
//        [self showAlertViewAboutNotAuthorAccessContact];
//    } else if (status == CNAuthorizationStatusAuthorized) {
//        //有权限
//        weakSelf.isRecommend = 1;
//        [self openContact];
//    }
//
//}
//
//- (void)openContact{
//
//    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
//    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
//    CNContactStore *contactStore = [[CNContactStore alloc] init];
//        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
//    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
//
//        NSString * firstName = contact.familyName;
//        NSString * lastName = contact.givenName;
//
//        //电话
//        NSArray * phoneNums = contact.phoneNumbers;
//        CNLabeledValue *labelValue = phoneNums.firstObject;
//        NSString *phoneValue = [labelValue.value stringValue];
//
////        NSLog(@"姓名：%@%@ 电话：%@", firstName, lastName, phoneValue);
//        if ([phoneValue containsString:@"-"]||[phoneValue containsString:@" "]) {
//            if ([phoneValue containsString:@"-"]) {
//               NSArray * phones = [phoneValue componentsSeparatedByString:@"-"];
//                NSString * phoneStr;
//                for (int i=0; i<phones.count; i++) {
//                    if (i==0) {
//                     phoneStr = [NSString stringWithFormat:@"%@",phones[i]];
//                    }else{
//                       phoneStr = [NSString stringWithFormat:@"%@%@",phoneStr,phones[i]];
//                    }
//
//                }
//                phoneValue = phoneStr;
//            }else{
//               NSArray * phones = [phoneValue componentsSeparatedByString:@" "];
//                NSString * phoneStr;
//                for (int i=0; i<phones.count; i++) {
//                    if (i==0) {
//                     phoneStr = [NSString stringWithFormat:@"%@",phones[i]];
//                    }else{
//                       phoneStr = [NSString stringWithFormat:@"%@%@",phoneStr,phones[i]];
//                    }
//
//                }
//                phoneValue = phoneStr;
//            }
//
//
//        }
//        if (phoneValue) {
//          [dic setValue:phoneValue forKey:[NSString stringWithFormat:@"%@%@",firstName,lastName]];
//        }
//
//
//    }];
////     NSLog(@"%@",dic);
//}

////获取多个联系人 里面只log了每个联系人第一个电话号码
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
//
//    //遍历
//
//    for (CNContact * contact in contacts) {
//
//        //姓名
//        NSString * firstName = contact.familyName;
//        NSString * lastName = contact.givenName;
//
//        //电话
//        NSArray * phoneNums = contact.phoneNumbers;
//        CNLabeledValue *labelValue = phoneNums.firstObject;
//        NSString *phoneValue = [labelValue.value stringValue];
//        NSLog(@"姓名：%@%@ 电话：%@", firstName, lastName, phoneValue);
//
//
//    }
//
//}

//- (void)showAlertViewAboutNotAuthorAccessContact{
//    dispatch_async(dispatch_get_main_queue(), ^{
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请授权通讯录权限" message:@"请在iPhone的\"设置-隐私-通讯录\"选项中,允许im解访问你的通讯录" preferredStyle: UIAlertControllerStyleAlert];
//    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self toSetSystemMsgPushPage];
//    }];
//    [alertController addAction:OKAction];
//    [self presentViewController:alertController animated:YES completion:nil];
//    });
//}

- (void)setSystemPushMsg{
    
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if(settings.authorizationStatus==UNAuthorizationStatusNotDetermined) {
                
                NSLog(@"未选择---没有选择允许或者不允许，按不允许处理");
                [self toSetSystemMsgPushPage];
            }else if(settings.authorizationStatus==UNAuthorizationStatusDenied){
                [self toSetSystemMsgPushPage];
                NSLog(@"未授权--不允许推送");
            }else if(settings.authorizationStatus==UNAuthorizationStatusAuthorized){
                [self toSetSystemMsgPushPage];
                NSLog(@"已授权--允许推送");
                
            }
            
        }];
    } else {
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        
        if (UIUserNotificationTypeNone == setting.types) {
            
            NSLog(@"推送关闭");
            [self toSetSystemMsgPushPage];
            
        }else{
            [self toSetSystemMsgPushPage];
            NSLog(@"推送打开");
            
        }
    }
    
}

- (void)toSetSystemMsgPushPage{
    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
     dispatch_async(dispatch_get_main_queue(), ^{
         if([[UIApplication sharedApplication] canOpenURL:url]) {
                NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }else{
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if([[UIApplication sharedApplication] canOpenURL:url]) {
                    
                    NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    
                    [[UIApplication sharedApplication] openURL:url];
                    
                }
                
            }
     });
    [self getSystemMesSet];
}

- (void)uploadSetDataWithData:(NSString *)on{
    
    [RequestData changeUserInfoWithToken:_model.token userUUid:_model.uuid areaStr:@"" withBirthday:@"" withCity:@"" withCompany:@"" withHead:@"" withIsVerify:on withJob:@"" withNickName:@"" withProvince:@"" withRemark:@"" withSex:@"" Success:^(NSDictionary * _Nonnull Dict) {
        [self showTipHudWithText:@"设置成功"];
    } failure:^(NSString * _Nonnull errMsg) {
        NSLog(@"修改信息失败%@",errMsg);
        [self showTipHudWithText:@"保存失败"];
    }];
}


- (void)signOutLoginActive:(UIButton *)sender{
    NSLog(@"退出登录");
    [[LoginManager shareLoginManager] saveLoginCustomer:[[UserModel alloc]init]];
    [[LoginManager shareLoginManager]loginOut];
    
}

-(UITableView *)setTableView{
    if (!_setTableView) {
        _setTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
        _setTableView.delegate = self;
        _setTableView.dataSource = self;
        _setTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _setTableView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 8.f)];
        headerView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        _setTableView.tableHeaderView = headerView;
    }
    return _setTableView;
}
-(UIView *)footView{
    if (!_footView) {
        _footView = [UIView new];
        _footView.backgroundColor = [UIColor clearColor];
    }
    return _footView;
}

- (UIButton *)signOutBtn{
    if (!_signOutBtn) {
        _signOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_signOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [_signOutBtn setTitleColor:KHEXCOLOR(@"ffffff") forState:UIControlStateNormal];
        [_signOutBtn setBackgroundColor:KHEXCOLOR(@"#4795EF")];
        _signOutBtn.layer.cornerRadius = 5;
        _signOutBtn.layer.masksToBounds = YES;
        [_signOutBtn addTarget:self action:@selector(signOutLoginActive:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _signOutBtn;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
